$(function() {
    // 定义操作事件
    window.operateEvents = {
        'click .edit': function (e, value, row, index) {
            $('#id').val(row.id);
            $('#no').val(row.no);
            $('#name').val(row.name);
            $('#password').val('');
            $('#sex').val(row.sex);
            $('#age').val(row.age);
            $('#score').val(row.score);
            $('#myModal').modal('show');
        },
        'click .remove': function (e, value, row, index) {
            if (confirm('确定删除该学生信息吗？')) {
                $.ajax({
                    url: '/api/student/deletebyid/' + row.id,
                    type: 'DELETE',
                    success: function(result) {
                        console.log('删除成功: ', result);
                        $('#students').bootstrapTable('refresh');
                    },
                    error: function(xhr, status, error) {
                        console.error('删除失败: ', status, error);
                    }
                });
            }
        }
    };

    // 初始化表格
    $("#students").bootstrapTable({
        method: "get",
        url: '/api/student/list3',
        cache: false,
        striped: true,
        pagination: true,
        sortable: false,
        sidePagination: "server",
        pageNumber: 1,
        pageSize: 3,
        pageList: [3, 5, 25],
        strictSearch: false,
        minimumCountColumns: 2,
        clickToSelect: true,
        uniqueId: "id",
        cardView: false,
        detailView: false,
        showFullscreen: true,
        showRefresh: true,
        showColumns: true,
        showColumnsToggleAll: true,
        queryParams: function(params) {
            return {
                pageSize: params.limit,
                pageNum: Math.floor(params.offset / params.limit) + 1
            };
        },
        columns: [{
            checkbox: true
        }, {
            field: 'id',
            title: '学生id'
        }, {
            field: 'no',
            title: '学号'
        }, {
            field: 'name',
            title: '姓名'
        }, {
            field: 'sex',
            title: '性别'
        }, {
            field: 'age',
            title: '年龄'
        }, {
            field: 'score',
            title: '分数'
        }, {
            field: 'operate',
            title: '操作',
            align: 'center',
            formatter: operateFormatter,
            events: operateEvents
        }]
    });

    // 操作列的格式化函数
    function operateFormatter(value, row, index) {
        return [
            '<a class="edit ml10" href="javascript:void(0)" title="编辑">',
            '编辑',
            '</a>  ',
            '<a class="remove ml10" href="javascript:void(0)" title="删除">',
            '删除',
            '</a>'
        ].join('');
    }

    // 初始化表单验证
    $("#formStudent").validate({
        submitHandler: function(form) {
            var id = $('#id').val();
            var formData = {
                id: id,
                no: $("#no").val(),
                name: $("#name").val(),
                password: $("#password").val(),
                sex: $("#sex").val(),
                age: $("#age").val(),
                score: $("#score").val()
            };
            var url, type;
            if (id == "0" || id == "") {
                url = "/api/student/insert";
                type = "POST";
            } else {
                url = "/api/student/update";
                type = "PUT";
            }
            $.ajax({
                url: url,
                type: type,
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(result) {
                    console.log("操作成功: ", result);
                    $('#myModal').modal('hide');
                    $('#students').bootstrapTable('refresh');
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error("操作失败: ", textStatus, errorThrown);
                }
            });
        }
    });

    // 提交表单事件处理
    $('#formStudent').off('submit').on('submit', function(e) {
        e.preventDefault();
        if ($(this).valid()) {
            // 使用submitHandler函数进行表单提交，避免递归调用
            $(this).validate().settings.submitHandler(this);
        }
    });
});


function preAdd() {
    $('#id').val("0"); //提示新增
    $('#formStudent').trigger('reset'); //重置表单
    $('#myModal').modal('show'); // 显示模态框
}

// 查询学生
function searchStudents() {
    var queryNo = $("#queryNo").val();
    var queryName = $("#queryName").val();
    var querySex = $("#querySex").val();
    var queryAgeRange = $("#queryAgeRange").val();
    var queryScoreRange = $("#queryScoreRange").val();

    var queryParams = {};
    if (queryNo !== "") queryParams.no = queryNo;
    if (queryName !== "") queryParams.name = queryName;
    if (querySex !== "") queryParams.sex = querySex;
    if (queryAgeRange !== "") queryParams.ageRange = queryAgeRange;
    if (queryScoreRange !== "") queryParams.scoreRange = queryScoreRange;

    $.ajax({
        url: "/api/student/search",
        type: "GET",
        data: queryParams,
        success: function(data) {
            console.log("查询成功: ", data);
            $('#students').bootstrapTable('load', data); // 使用新的数据更新表格
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error("查询失败: ", textStatus, errorThrown);
        }
    });
}



